#include <iostream>
#include <atomic>
#include <thread>
#include <functional>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <sstream>
#include <atomic>
#include <functional>
#include <cstring>
#include "mysql_connection_pool.h"
#include "thread_pool.h"
#include "database_service.h"

int main() {
    // 初始化连接池（10个连接）
    MySQLConnectionPool conn_pool("47.96.159.221", "root", "123456", "finance_data", 10);

    // 初始化线程池（建议设置为CPU核心数×2）
    const size_t thread_pool_size = std::thread::hardware_concurrency() * 2;
    ThreadPool pool(thread_pool_size, conn_pool);

    // 初始化数据库服务
    DatabaseService service(conn_pool);

    // 原子计数器用于跟踪完成的任务
    std::atomic<int> completed_tasks{ 0 };
    const int TOTAL_TASKS = 50;

    // 提交50个插入任务
    for (int i = 0; i < TOTAL_TASKS; ++i) {
        pool.enqueue([&service, i, &completed_tasks] {
            try {
                std::string name = "User_" + std::to_string(i);
                std::string email = "user_" + std::to_string(i) + "@example.com";
                service.insertData(name, email);
                std::cout << "Inserted: " << name << std::endl;
                completed_tasks++;
            }
            catch (const std::exception& e) {
                std::cerr << "Task error: " << e.what() << std::endl;
            }
        });
    }

    // 等待所有任务完成（生产环境应使用条件变量）
    while (completed_tasks < TOTAL_TASKS) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    // 验证结果
    service.readData();

    return 0;
}